<template>
    <div class="compare__layout">

        <!-- 对比内容载体 -->
        <div class="compare__main"
            v-loading="contentloading"
            :style="formatCompareStyle">
            

            <!-- 左侧的快捷菜单 -->
            <ul class="compare__menu"
                :style="formatMenuStyle">
                <li class="menu-title">快捷列表</li>
                <li :class="{ active: scroll.activeStep == index }" 
                    v-for="(item, index) in result.compareSetting" :key="index"
                    @click="scrollToCurrentStep(index)">
                    {{ item.name }}
                </li>
            </ul>
            

            <!-- 右侧的添加新对比对象 -->
            <div class="compare__addSort" v-show="result.initNumber < maxNumber"
                :style="formatAddStyle"
                @click="addNewCompare">
                添加对比
            </div>


            <!-- 对比的对象详情显示 -->
            <div class="compare__queryobj" :style="formatQueryStyle">
                <div class="queryobj-cell style-line">
                    <slot name="querytitle"></slot>
                </div>

                <div class="queryobj-cell" 
                    v-for="(item, index) in result.initNumber" :key="index" :slotIndex="index">
                    <div class="compare-close el-icon-close" 
                        v-if="(index + 1) > minNumber"
                        @click="removeOldCompare(index)">
                    </div>
                    <slot :name="index"></slot>
                </div>
            </div>

            
            <CompareScroll
                ref="betterscroll"
                @scrollReady="scrollReady"
                @scrollChange="scrollChange" 
                :style="formatScrollStyle">

                <div class="compare__scroll">
                    <CompareItem
                        ref="listGroup"
                        v-for="(item, index) in result.compareSetting" :key="index"
                        :size="colSize"
                        :option="item"
                        :dataInfo="result.compareResultData">
                    </CompareItem>
                </div>
                
            </CompareScroll>
        </div>


        <!-- 返回顶部按钮 -->
        <div class="compare__top" v-show="formatTopButtonShow" @click="scrollToTop">
            <div title="返回顶部" class="scroll-btn">
               <i class="el-icon-caret-top"></i> 
            </div>
        </div>




        <!-- 拓展插槽 -->
        <slot></slot>
    </div>
</template>
<script>
    import CompareScroll from './CompareScroll.vue';
    import CompareItem from './CompareTable.vue';

    export default {
        name: '',
        components: { CompareScroll, CompareItem },
        props: {
            fillString: {
                type: String,
                default: '-'
            },  

            useSize: {
                type: Object,
                default: () => {
                    return {
                        headerheight: 120,

                        menuheight: '50%',

                        menuwidth: '100px'
                    }
                }
            },

            minNumber: {                        //  最少数量
                type: Number,
                default: 4,
            },
            maxNumber: {                        //  最多数量
                type: Number,
                default: 6
            },
            colSize: {                             //  default
                type: String,
                default: 'default'
            }
        },
        data() {
            return {
                contentloading: false,

                sizeMatch: {
                    'default': { width: 200, height: 40 },
                    'big': { width: 220, height: 50 }
                },

                scroll: {
                    // 每一段内容的高度位置
                    stepHeightList: [],
                    // 当前滚动位置
                    currentHeight: 0,
                    // 当前在第几个层级
                    activeStep: 0,
                    // 滚动条总共高度
                    totalHeight: 0,
                },

                result: {
                    initNumber: 4,
                    compareSetting: null,
                    compareResultData: [],
                },

            }
        },
        computed: {
            formatCompareStyle() {
                return `width: ${ (this.result.initNumber + 1) * this.sizeMatch[this.colSize].width }px`
            },

            formatAddStyle() {
                const { headerheight } = this.useSize
                return `top: ${ headerheight }px`
            },

            formatMenuStyle() {
                const { headerheight, menuheight, menuwidth } = this.useSize
                return `top: ${ headerheight }px; max-height: ${ menuheight }; width: ${ menuwidth }; left: calc( -${ menuwidth } - 15px)`
            },

            // 返回顶部按钮，超出总长度 1 / 3 的时候显示出来
            formatTopButtonShow() {
                return this.scroll.currentHeight > (this.scroll.totalHeight / 3)
            },

            formatScrollStyle() {
                const { headerheight } = this.useSize
                return `height: calc(100% - ${ headerheight }px)`
            },

            formatQueryStyle() {
                const { headerheight } = this.useSize
                return `height: ${ headerheight }px`
            }
        },
        methods: {
            /**
             * 需要对比的东西进行格式化，可以动态改变格式数据
             * 这样动态显示数据对比内容了呀
             * @param {*} insideSetting 
             */
            async readyDataInfoObj(insideSetting, number) {
                this.result.initNumber = number
                await this.$nextTick()

                const formatDataResult = {}
                const compareData = new Array(this.result.initNumber).fill(this.fillString)

                insideSetting.forEach(item => {
                    item.children.forEach(rule => {
                        const { name, sort, sign } = rule
                        formatDataResult[sign] = {
                            name,
                            sort,
                            sign,
                            max: null,
                            min: null,
                            dataList: [...compareData]
                        }
                    })
                })
                this.result.compareSetting = insideSetting
                this.result.compareResultData = formatDataResult
                await this.$nextTick()
                this.recordScrollHeight()
            },
            
            
            refreshCompareData(newCompare, index) {
                const foramtData = JSON.parse(JSON.stringify(newCompare))
                const keyList = Object.keys(this.result.compareResultData)

                keyList.forEach(key => {
                    if(!this.result.compareResultData[key]) return
                    const replaceData = this.checkCompareRule(foramtData[key])
                    this.result.compareResultData[key].dataList.splice(index, 1, replaceData)
                })

                Object.values(this.result.compareResultData).forEach(item => {
                    const { sort, dataList } = item
                    // 如果是需要排序的那种情况，找最大最小值
                    if(sort) {
                        let sortDataList = dataList.filter(num => isFinite(num))
                        item.min = Math.min(...sortDataList)
                        item.max = Math.max(...sortDataList)
                    }
                })
            },  

            /**
             * 
             * 限制数据的显示格式
             * @param {*} value 
             * 
             */
            checkCompareRule(value) {
                if(value === undefined || value === null || value === '' || value == []) {
                    return '-'
                } else {
                    const type = Object.prototype.toString.call(value)
                    if(['[object String]', '[object Number]', '[object Boolean]'].includes(type)) {
                        return value
                    } else if(type === '[object Array]' ) {
                        return value.join(', ')
                    } else {
                        return '数据类型不支持显示/对比'
                    }
                }
            },
            
            /**
             * 
             * 添加对比对象
             * 
             */
            addNewCompare() {
                if((this.result.initNumber + 1) > this.maxNumber) return
                this.result.initNumber ++
                Object.values(this.result.compareResultData).forEach(item => {
                    item.dataList = item.dataList.concat(this.fillString)
                })
                this.$emit('sortChange', -1)
            },

            /**
             * 
             * 移除对比对象
             * @param {*} index 
             * 
             */
            removeOldCompare(index) {
                if((this.result.initNumber - 1) < this.minNumber) return
                this.result.initNumber --
                Object.values(this.result.compareResultData).forEach(item => {
                    item.dataList.splice(index, 1)
                })
                this.$emit('sortChange', index)
            },






            /**
             * 
             * 
             * 
             * 
             * 
             * 
             * @tips
             * 下面的代买都是
             * 布局联动，无关业务，无需特别在意，如有问题，喊出来
             * 
             * 
             * 
             * 
             * 
             * 
             * 
             * 
             * 
             * 
             * 
             */


            scrollReady(scroll) {
                this.scroll.totalHeight = scroll.wrapperHeight
            },


            scrollChange(pos) {
                this.scroll.currentHeight = Math.abs(pos.y)
                this.scroll.activeStep = this.scroll.stepHeightList.findIndex(y => y >= this.scroll.currentHeight)
            },

            /**
             * 
             * 快捷菜单滚动到合适的位置，也可以通过外界传递
             * @param {*} index 
             * 
             */
            async scrollToCurrentStep(index) {
                this.scroll.activeStep = index
                let currentScroll = this.scroll.stepHeightList[index]
                
                const bottomScroll = this.scroll.stepHeightList.slice(-1)
                if((bottomScroll - currentScroll) <= this.scroll.totalHeight ) {
                    currentScroll = bottomScroll - this.scroll.totalHeight
                }
                this.scroll.currentHeight = currentScroll

                await this.$nextTick()
                const { headerheight } = this.useSize
                this.$refs.betterscroll.scrollTo(0, -currentScroll, headerheight)
            },




            /**
             * 
             * 记录下来每个模块的高度，然后方便做快捷菜单用
             * 
             */
            recordScrollHeight() {
                const domList = this.$refs.listGroup
                let height = 0
                this.scroll.stepHeightList.push(height)

                domList.forEach(el => {
                    height += el.$el.clientHeight
                    this.scroll.stepHeightList.push(height)
                })
            },


            async scrollToTop() {
                this.scroll.currentHeight = 0
                this.scroll.activeStep = 0
                await this.$nextTick()
                const { headerheight } = this.useSize
                this.$refs.betterscroll.scrollTo(0, 0, headerheight)
            }


        },
        beforeCreate() {

        },
        created() {

        },
        beforeMount() {

        },
        mounted() {

        },
        beforeDestroy() {

        },
    }
</script>
<style lang="scss" scoped>
.compare {
    &__layout {
        position: relative;
        width: 100%;
        height: 100%;
        // background-color: var(--background-color-base); 
    }


    &__main {
        margin: auto;
        height: 100%;
        position: relative;
        box-shadow: var(--box-shadow-base);
        transition: all 0.3s ease-in-out;
    }

    &__queryobj {
        position: relative;
        display: flex;
        box-shadow: var(--box-shadow-base);
        z-index: 2;

        .style-line {
            background: linear-gradient(25deg, transparent 48.5%, var(--background-color-base) 50.5%, var(--background-color-base) 50.5%, transparent 50.5%)
        }

        .queryobj-cell {
            flex: 1;
            position: relative;
            border-right: solid 1px var(--border-color-base);

            &:last-child {
                border: 0;
            }

            .compare-close {
                position: absolute;
                z-index: 10;
                top: var(--default-padding);
                right: var(--default-padding);
                cursor: pointer;
                background-color: var(--background-color-base);
                width: 20px;
                height: 20px;
                font-size: 14px;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }

    &__menu {
        position: absolute;
        background-color: var(--background-color-base);
        box-shadow: var(--box-shadow-base);
        border-radius: 4px;
        padding: 2px 0;
        cursor: pointer;
        overflow: auto;

        li {
            padding: 6px 10px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;

            &.menu-title {
                // background-color: var(--background-color-light);
                border-bottom: solid 1px var(--border-color-base);
                cursor: auto;
            }
    
            &.active {
                background-color: var(--color-primary);
                color: var(--color-white);
            }
        }
    }

    &__top {
        position: absolute;
        right: 20px;
        bottom: 20px;

        .scroll-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            height: 50px;
            width: 50px;
            font-size: 20px;
            border-radius: 50%;
            box-shadow: var(--box-shadow-base);
            background-color: var(--background-color-base);

            &:hover {
                background-color: var(--color-primary);
                color: var(--color-white);
            }
        }
    }

    &__addSort {
        position: absolute;
        right: -45px;
        background-color: var(--background-color-base);
        box-shadow: var(--box-shadow-base);
        border-radius: 4px;
        width: 30px;
        padding: 6px;
        cursor: pointer;
        line-height: 25px;
        text-align: center;

        &:hover {
            background-color: var(--color-primary);
        }
    }

    &__scroll {
        position: relative;
    }
}
</style>